package com.test.gwt.mvp.client.ui;

import java.util.List;

import org.eclipse.jetty.util.log.Log;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SingleSelectionModel;
import com.test.gwt.mvp.shared.Mail;

public class MailListViewImpl extends Composite implements MailListView {

	private static MailListViewImplUiBinder uiBinder = GWT
			.create(MailListViewImplUiBinder.class);

	interface MailListViewImplUiBinder extends
			UiBinder<Widget, MailListViewImpl> {
	}
	
	@UiField
	CellTable<Mail> table;

	final SingleSelectionModel<Mail> selectionModel;
	
	private Presenter presenter;
	
	
	public MailListViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
		TextColumn<Mail> sender = new TextColumn<Mail>() {
			@Override
			public String getValue(Mail object) {
				return object.getSender();
			}
		};
		TextColumn<Mail> subject = new TextColumn<Mail>() {
			@Override
			public String getValue(Mail object) {
				return object.getSubject();
			}
		};	
		table.addColumn(sender);
		table.addColumn(subject);
		selectionModel = new SingleSelectionModel<Mail>();
		table.setSelectionModel(selectionModel);
		addOnSelectionChangeHandler();
	}

	@Override
	public void setMailList(List<Mail> mailList) {
		table.setRowData(mailList);
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}
	
	
	private void addOnSelectionChangeHandler(){
		selectionModel.addSelectionChangeHandler(new Handler() {
			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				GWT.log("onSelectionChange ...");
				Mail mail = selectionModel.getSelectedObject();
				presenter.mailSelected(mail.getId());
			}
		});
	}
}
